<?php


namespace App\Models;

use App\Http\Controllers\WebApi\Business\ConfigBusiness;
use App\Jobs\GroupTask;
use App\Services\Configs\DefaultService;
use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Services\Huanxin\GroupServices;
use App\Services\RongCloud\GroupService;
use App\Services\Netease\GroupServices as NetGroupServices;
use Illuminate\Support\Facades\Redis;

class ImGroup extends BaseModel
{
    use SoftDeletes;
    protected $table = 'im_group';

    //群主用户信息
    public function groupManager()
    {
        return $this->belongsTo(ImUsers::class, 'user_id', 'id')->select(['id', 'nickname', 'headimg', 'sex', 'phone']);
    }

    /**
     * 关联的群组id
     */
    public function relate_single()
    {
        return $this->belongsTo(ImGroupRelate::class, 'im_gid', 'im_gid');
    }

    /**
     * @desc 新增群组
     * @param array $input 传过来数组对象
     * @param int $userId 用户id
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/11/23 14:58
     */
    public function addGroup($input, $userId)
    {
        $this->name = $input['name'];
        $this->description = $input['desc'] ?? '';
        $this->open = $input['open'];
        $this->max_count = $input['max_count'];
        $this->users_count = $input['users_count'];
        $this->is_allow = $input['is_allow']; // 1 允许 0 不允许， 允许的话，不需要审核 $membersonly true； 不允许话，需要审核false， 默认false
        $this->user_id = $userId;

        $option = ConfigBusiness::thirdPartyFirst('im');
        $optionValue = $option->value;
        $member = $input['member'] ?? '';
        $memberList = !empty($member) ?  explode(",",$member) : [];
        switch($optionValue)
        {
            case ($optionValue == DefaultService::HUANXIN_IM):  // 环信
                $groupServices= new GroupServices();
                $public = ($input['open'] == 1) ? true : false; // 1公开，2私有
                $allow = ($input['is_allow'] == 1) ? true : false; // 0：不允许，1：允许
                $audit = ($input['is_allow'] == 1) ? true : false; // true 不需要审核， false 需要审核
                $groupServiceInfo = $groupServices->createGroup($input['name'],$input['desc'], $public, $allow, $audit, strval($userId));
                if ($groupServiceInfo['code'] != 200)
                {
                    return ['code' => 1];
                }
                $this->im_gid = $groupServiceInfo['data']['data']['groupid'];

                GroupTask::dispatch(['group_id'=>$this->im_gid,'member_id'=>$input['member'],'group_name'=>$input['name'],'user_id'=>$userId,'type'=>1]);
                break;
            case ($optionValue == DefaultService::RONGYUN_IM):  // 融云
                $groupServices= new GroupService();
                $phrase = new PhraseBuilder(13, '0123456789');
                $CaptchaBuilder = new CaptchaBuilder(null, $phrase);
                $captcha = $CaptchaBuilder->getPhrase();
                $this->im_gid = "16".$captcha;
                $this->type = 2;
                $groupServiceInfo = $groupServices->create($userId, $this->im_gid, $input['name']);
                if ($groupServiceInfo['code'] != 200)
                {
                    return ['code' => 1];
                }

                GroupTask::dispatch(['group_id'=>$this->im_gid,'member_id'=>$input['member'],'group_name'=>$input['name'],'user_id'=>$userId,'type'=>2]);
                break;
            case ($optionValue == DefaultService::NETEASE_IM):  // 网易云信
                $groupServices= new NetGroupServices();
                $audit = ($input['is_allow'] == 1) ? true : false; // true 不需要审核， false 需要审核
                $groupServiceInfo = $groupServices->createGroup($input['name'],strval($userId), $memberList, '欢迎入群', '',  $input['desc'], 0, $audit, 0);
                if ($groupServiceInfo['code'] != 200)
                {
                    return ['code' => 1];
                }
                $this->im_gid = $groupServiceInfo['data']['tid'];
                $this->type = 3;
                GroupTask::dispatch(['group_id'=>$this->im_gid,'member_id'=>$input['member'],'group_name'=>$input['name'],'user_id'=>$userId,'type'=>3]);
                break;
        }

        $this->is_audit = ($input['is_allow'] == 1) ? 0 : 1;
        $flag = $this->save();
        if (!$flag)
        {
            return ['code' => 1];
        }

        // 群组默认加入里面
        $ImGroupMasterModel = new ImGroupUser();
        $ImGroupMasterModel->im_gid = $this->im_gid;
        $ImGroupMasterModel->user_id = $userId;
        $ImGroupMasterModel->role = 1;
        $ImGroupMasterModel->save();
        $this->increment('users_count');


        if ($member)
        {
            switch($optionValue)
            {
                case ($optionValue == DefaultService::HUANXIN_IM):  // 环信
                    $service['usernames'] = $memberList;
                    $groupServices= new GroupServices();
                    $groupServiceInfo = $groupServices->addChatGroupsMembers($this->im_gid, $service);
                    if ($groupServiceInfo['code'] != 200)
                    {
                        return ['code' => 1, 'msg' => '添加失败'];
                    }
                    break;
                case ($optionValue == DefaultService::RONGYUN_IM):  // 融云
                    $groupServices= new GroupService();
                    $memberList = explode(",",$member);
                    $groupServiceInfo = $groupServices->joinGroup($input['member'], $this->im_gid, $input['name']);
                    if ($groupServiceInfo['code'] != 200)
                    {
                        return ['code' => 1];
                    }
                    break;
                default:
                    break;
            }

            // 新增群组组员
            $ImGroupUserModel = new ImGroupUser();
            $ImGroupUserModel->addMoreMemebr($member, $this->im_gid, $userId);

            $this->increment('users_count', count($memberList));

            $fileUrl = $ImGroupUserModel->updateGroupHeading($this->im_gid);
            if ($fileUrl)
            {
                $this->face = $fileUrl;
                $this->save();
            }
        }

        return ['code' => 0, 'id' => $this->id, 'data'=>['group_id' => $this->im_gid, 'face'=>$fileUrl]];
    }


    /**
     * @desc 编辑群组信息
     * @param array $input 传过来的数组对象
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/11/23 14:58
     */
    public function editGroup($input)
    {
        $groupServices= new GroupServices();
        $groupServiceInfo = $groupServices->updateGroup($input['name'], $input['description'],
            $input['is_allow'] == 1 ? true : false, true, $input['open'] == 1 ? true : false, $input['im_gid']);
        if ($groupServiceInfo['code'] != 200)
        {
            return ['code' => 1, 'msg' => '修改失败'];
        }

        $flag = $this->where('im_gid', $input['im_gid'])->update($input);
        if (!$flag)
        {
            return ['code' => 1, 'msg' => '修改失败'];
        }

        return ['code' => 0, 'msg' => '修改成功'];
    }

    /**
     * @desc 删除群组
     * @param string $imGid 群组环信id
     * @param int $userId 用户id
     * @return array
     * @author zhouzhou
     * @time 2021/11/23 16:06
     */
    public function delGroup($imGid, $userId)
    {
        $imGroup = $this->where('im_gid', $imGid)->first();
        if (!$imGroup)
        {
            return ['code' => 1, 'msg' => '删除失败'];
        }

        if ($imGroup['user_id'] != $userId)
        {
            return ['code' => 1, 'msg' => '非群主不能删除'];
        }

        $option = ConfigBusiness::thirdPartyFirst('im');
        $optionValue = $option->value;
        switch($optionValue)
        {
            case ($optionValue == DefaultService::HUANXIN_IM):  // 环信
                $groupServices= new GroupServices();
                $groupServiceInfo = $groupServices->deleteGroup($imGid);
                break;
            case ($optionValue == DefaultService::RONGYUN_IM):  // 融云
                $groupServices= new GroupService();
                $groupServiceInfo = $groupServices->dismiss($userId, $imGid);
                break;
            case ($optionValue == DefaultService::NETEASE_IM):  // 网易
                $groupServices= new NetGroupServices();
                $groupServiceInfo = $groupServices->removeGroup($imGid, $userId);
                break;
            default:
                $groupServiceInfo['code'] = 400;
                break;
        }

        if ($groupServiceInfo['code'] != 200)
        {
            return ['code' => 1, 'msg' => '修改失败'];
        }

        $imGroup->delete();
        if ($imGroup->trashed())
        {
            return ['code' => 0, 'msg' => '解散成功'];
        }
        else
        {
            return ['code' => 1, 'msg' => '删除失败'];
        }
    }

    /**
     * @desc 设置群公告群主和管理员可以设置
     * @param array $input 传过来数组对象
     * @param int $userId 用户id
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/11/23 14:58
     */
    public function setGroupSummery($input, $userId = 0)
    {
        $imGroup = $this->where('im_gid', $input['im_gid'])->first();
        if (!$imGroup)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        $imGroupUser = new ImGroupUser();
        $imGroupUser = $imGroupUser->where(['im_gid' => $input['im_gid'], 'user_id' => $userId])->whereIn('status', [0,3])->first();
        if (!$imGroupUser)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        if ($imGroupUser && !in_array($imGroupUser['role'], [1,2]))
        {
            return ['code' => 1, 'msg' => '权限不足'];
        }

        $imGroup->summary = $input['summary'];
        $flag = $imGroup->save();

        if (!$flag)
        {
            return ['code' => 1, 'msg' => '发布失败'];
        }

        $imGroupSummery = new ImGroupSummery();
        $imGroupSummery->im_gid = $input['im_gid'];
        $imGroupSummery->user_id = $userId;
        $imGroupSummery->summary = $input['summary'];
        $imGroupSummery->save();

        return ['code' => 0, 'id' => $this->id, 'msg' => '添加成功'];
    }

    /**
     * @desc 修改设置全员禁言群主和管理员可以设置
     * @param array $input 传过来数组对象
     * @param int $userId 用户id
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/11/23 14:58
     */
    public function setAllBanned($input, $userId = 0)
    {
        $imGroup = $this->where('im_gid', $input['im_gid'])->first();
        if (!$imGroup)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        $imGroupUser = new ImGroupUser();
        $imGroupUser = $imGroupUser->where(['im_gid' => $input['im_gid'], 'user_id' => $userId])->whereIn('status', [0,3])->first();
        if (!$imGroupUser)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        if ($imGroupUser && !in_array($imGroupUser['role'], [1,2]))
        {
            return ['code' => 1, 'msg' => '权限不足'];
        }

        $imGroup->is_all_banned = $input['is_all_banned'];
        $flag = $imGroup->save();

        if (!$flag)
        {
            return ['code' => 1, 'msg' => '操作失败'];
        }

        return ['code' => 0, 'msg' => '操作成功'];
    }

    /**
     * @desc 群组详情
     * @param string $imGid 群组的id
     * @param int $userId 用户id
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/11/23 14:58
     */
    public function detail($imGid, $userId = 0)
    {
        $imGroup = $this->where('im_gid', $imGid)->first();

        if (!$imGroup)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        $imGroupUser = new ImGroupUser();
        $imGroupUser = $imGroupUser->where(['im_gid' => $imGid, 'user_id' => $userId])->whereIn('status', [0,3])->first();

        $imGroup->top = $imGroupUser['top'] ?? 0;
        $imGroup->no_disturb = $imGroupUser['no_disturb'] ?? 0;
        $imGroup->note_name = $imGroupUser['note_name'] ?? '';
        $imGroup->show_name = $imGroupUser['show_name'] ?? '';
        $imGroup->chat_cover = $imGroupUser['chat_cover'] ?? '';
        $imGroup->role = $imGroupUser['role'] ?? 0;
        $imGroup->user_status = $imGroupUser['status'] ?? 1;
        $imGroup->is_join_group = !empty($imGroupUser) ? 1 : 0;

        return ['code' => 0, 'msg' => '系统', 'data'=>$imGroup];;
    }

    /**
     * @desc 关联的群组id
     * @param int $type 1环信，2融云 3网易
     * @return array
     * @author zhouzhou
     * @time 2021/12/27 16:21
     */
    public function relateGroupList($type)
    {
        $list = $this->select('id', 'im_gid', 'user_id','type')->with(['relate_single' => function($q) use($type){
            $q->select('im_gid','relate_gid','type');
            $q->where('type','=', $type);
        }])->where(['status'=>0])
            ->orderBy('id', 'desc')
            ->get();
        $netease = [];
        foreach ($list as $key =>&$val)
        {
            if (($val['type'] == $type) || !empty($val['relate_single']))
            {
                $netease[$key]['im_gid'] = ($val['type'] == $type) ? $val['im_gid'] : $val['relate_single']['relate_gid'];
                $netease[$key]['user_id'] = $val['user_id'];

            }
        }

        $netease = array_values($netease);

        return $netease;
    }


}
